package main

import (
	"context"
	"google.golang.org/grpc/credentials"
	"log"
	"os"
	"time"

	"google.golang.org/grpc"
	pb "linclaus.com/cmd/grpc/hello" // 替换为实际的包路径
)

func main() {
	// 连接到服务端
	creds, err := credentials.NewClientTLSFromFile("certs/ca.crt", "server.example.com")
	if err != nil {
		log.Fatalf("failed to create credentials: %v", err)
	}

	conn, err := grpc.Dial("localhost:50051", grpc.WithTransportCredentials(creds), grpc.WithBlock())
	//conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	c := pb.NewGreeterClient(conn)

	// 超时设置
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	// 准备请求
	name := "World"
	if len(os.Args) > 1 {
		name = os.Args[1]
	}
	// grpcurl -plaintext -import-path . -proto hello/hello.proto localhost:50051 list
	// grpcurl -plaintext -import-path . -proto hello/hello.proto localhost:50051 describe helloworld.Greeter
	// grpcurl -plaintext -d '{"name": "World"}' -import-path . -proto hello/hello.proto localhost:50051 helloworld.Greeter.SayHello
	// grpcurl -plaintext -d '{"name": "World"}' -import-path . -proto hello/hello.proto localhost:50051 helloworld.Greeter.SayHelloStream
	// grpcurl -plaintext -d @ -import-path . -proto hello/hello.proto localhost:50051 helloworld.Greeter.SayHelloClientStream
	// grpcurl -plaintext -d @ -import-path . -proto hello/hello.proto localhost:50051 helloworld.Greeter.SayHelloBidiStream
	// grpcurl -d '{"name": "World"}'  -cacert certs/ca.crt -import-path . -proto hello/hello.proto server.example.com:50051  helloworld.Greeter.SayHello
	// grpcurl -servername server.example.com -d '{"name": "World"}'  -cacert certs/ca.crt -import-path . -proto hello/hello.proto localhost:50051  helloworld.Greeter.SayHello

	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.GetMessage())
}
